﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace waveform_test
{
    public partial class LogForm : Form
    {
        public LogForm()
        {
            InitializeComponent();
        }

        public void UpdateLogTextbox(string value)
        {
            // Check whether invoke is required and then invoke as necessary
            if (InvokeRequired)
            {
                // this.BeginInvoke(new Action<string>(UpdateLogTextbox), new object[] { value });
                this.BeginInvoke(new MethodInvoker(delegate { UpdateLogTextbox(value); }));
                return;
            }

            // Set the textbox value
            LogTxt.Text = value;
            LogTxt.SelectionStart = LogTxt.Text.Length;
            LogTxt.ScrollToCaret();
        }

        private void LogForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Hide();
            if(e.CloseReason == CloseReason.UserClosing)
                e.Cancel = true;
        }

        private void BuscarBtn_Click(object sender, EventArgs e)
        {
            BuscarBtn.Enabled = false;

            if (BuscarTxt.Text != string.Empty)
            {
                LogTxt.SelectAll();
                LogTxt.SelectionBackColor = LogTxt.BackColor;
                LogTxt.SelectionStart = LogTxt.Text.Length;
                LogTxt.ScrollToCaret();

                int index = 0;

                while (index < LogTxt.Text.LastIndexOf(BuscarTxt.Text))
                {
                    // Searches the text in a RichTextBox control for a string within a range of text within the control and with specific options applied to the search.
                    LogTxt.Find(BuscarTxt.Text, index, LogTxt.TextLength, RichTextBoxFinds.None);
                    // Selection Color. This is added automatically when a match is found.
                    LogTxt.SelectionBackColor = Color.Yellow;
                    // After a match is found the index is increased so the search won't stop at the same match again. This makes possible to highlight same words at the same time.
                    index = LogTxt.Text.IndexOf(BuscarTxt.Text, index) + 1;
                }

                LogTxt.SelectionStart = LogTxt.Text.Length;
            }

            BuscarBtn.Enabled = true;
        }
    }
}
